package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feiggn.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


import java.awt.font.TextMeasurer;
import java.sql.Time;
import java.util.List;

@Component
@Getter
@Setter
public class MyinitProductJob  implements SimpleJob {

    @Value("${jobCron.initSeckillProduct}")
    private  String initSeckillProduct;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("分片参数:" +shardingContext.getShardingParameter());
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String shardingParameter) {
        //把之前的数据清空掉
        template.delete(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(shardingParameter));
        template.delete(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(shardingParameter));
        //远程调用秒杀服务
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.querySecKillVo(Integer.parseInt(shardingParameter));
          //如果没有问题那么就进入
         if (result != null && !result.hasError()){
             List<SeckillProductVo> list = result.getData();

             //有值就放到redis中
              if (list != null && list.size() >0){
                  for (SeckillProductVo seckillProductVo : list) {
                      template.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(shardingParameter),seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));
                      //库存放入到redis中
                      template.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(shardingParameter),seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");
                  }
                  System.out.println("数据初始化成功" + shardingParameter);
              }
         }

    }
}
